package persistencia.csv;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Collection;
import java.util.regex.Pattern;

public class LectorCSV extends Reader {

	protected BufferedReader entrada;
	protected Pattern patron;
	boolean fin;
	
	public LectorCSV (String archivo, String separadores) throws FileNotFoundException {
		FileReader fr = new FileReader(archivo);
		entrada = new BufferedReader(fr);
		patron = Pattern.compile(separadores);
		fin = false;
	}
	
	public String[] leer() throws IOException {
		String[] campos = null;
		String linea = null;
		if (!fin) {
			linea = entrada.readLine();
			fin = (linea == null);
		}
		if (!fin)
			campos = patron.split(linea);
		return campos;
	}
	
	public void leer(Collection<String> registro) throws IOException {
		for (String campo : this.leer())
			registro.add(campo);
	}
	
	@Override
	public int read(char[] cbuf, int off, int len) throws IOException {
		return entrada.read(cbuf, off, len);
	}

	@Override
	public void close() throws IOException {
		entrada.close();
	}
	
}
